<!--
 * @Author: LiYuan
 * @Date: 2021-03-30 09:48:07
 * @LastEditTime: 2022-10-25 15:00:08
 * @LastEditors: 川杨
 * @Description: 事件信息
 * You build it, You run it.
-->
<template>
  <div> 
    <form-view class="task-tab-container task-view-containner bbx-cell-form-view" :fields="fields" :form-cell-count="formCellCount" :value="event" mode="event" :biz-id="event.id">
      <template slot="eventNo" slot-scope="{ field, value }">
        <!-- start 事件编号 -->
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">{{ value }}</div>
        </div>
        <!-- end 事件编号 -->

        <!-- start 事件类型 -->
        <div class="form-view-row bbx-form-cell-item">
          <label>{{$t('event.eventType')}}</label>
          <div class="form-view-row-content">{{ event.templateName }}</div>
        </div>
        <!-- end 事件编号 -->
      </template>
      
      <!-- start 客户 -->
      <template slot="customer" slot-scope="{field}">
        <!-- start 客户 -->
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content customer-info">
            <div v-if="canSeeCustomer && event.cusName && event.cusId" class="customer-info-wrap" @click="openCustomer">
              <span class="customer-name link">{{event.cusName}}</span>
              <el-tooltip v-if="customerRelationCount.all > 0" placement="top">
                <div slot="content" v-html="$t('event.detail.components.eventInfo.text2', {data1: customerRelationCount.unfinished, data2: customerRelationCount.all})"></div>
                <el-button class="relation-count-button" @click="openCustomer" v-track="$track.formatParams('CHECK_CUSTOMER_EVENT_NUM')">
                  {{ `${customerRelationCount.unfinished}/${customerRelationCount.all}` }}
                </el-button>
              </el-tooltip>

              <el-tooltip v-if="event.attribute && event.attribute.tenantTagList && event.attribute.tenantTagList.length" placement="top">
                <div slot="content">
                  {{ customerTagValue(event.attribute.tenantTagList) }}
                </div>
                <base-tags :value="customerLabel(event.attribute.tenantTagList)" />
              </el-tooltip>

            </div>
            <div v-else>
              {{event.cusName}}
            </div>
            <el-button size="mini" v-if="!(isCusExist && isLmExist && isAddExist) && hasCusCreate" @click="saveCusInfo">{{$t('event.detail.components.eventInfo.text1')}}</el-button>
          </div>
        </div>
        <!-- end 客户 -->

        <!-- start 联系人 -->
        <div class="form-view-row bbx-form-cell-item" v-if="customerOption.linkman">
          <label>{{$t('common.base.contact')}}</label>
          <div class="form-view-row-content flex-x jus-bet">
            <div>{{event.lmName || '' + ' '}}{{event.lmEmail ? event.lmEmail : ''}}</div>
            <!-- <el-button @click="saveLinkman" v-if="!event.lmId && event.cusId && doorGray">保存联系人</el-button> -->
          </div>
        </div>
        <!-- end 联系人 -->

         <!-- start 电话 -->
        <div class="form-view-row bbx-form-cell-item" v-if="customerOption.linkman">
          <label>{{$t('common.base.phone')}}</label>
          <div class="form-view-row-content flex-x jus-bet">
            <div>{{event.lmPhone ? event.lmPhone+ ' ' : ' '}}</div>
          </div>
        </div>
        <!-- end 电话 -->

        <!-- start 地址 -->
        <form-address-view 
          class="bbx-form-cell-item"
          v-if="field.setting && field.setting.customerOption && field.setting.customerOption.address"
          :field="{ displayName: $t('common.base.locationMap.address') }"
          :value="event.cusAddress" 
        >
        </form-address-view>
        <!-- end 地址 -->

        <!-- start 产品 -->
        <template v-if="customerOption.product">
          <div class="form-view-row bbx-form-cell-item" v-if="!event.products.length"><label>{{$t('common.base.product')}}</label></div>
          <div class="product-list bbx-form-item" v-else>
            <div class="product-item" v-for="product in event.products" :key="product.id">
              <div class="product-item-name form-view-row">
                <label>{{$t('common.base.product')}}</label>
                <div class="form-view-row-content">
                  <span
                    class="link-text"
                    :key="product.id"
                    @click="openProductView(product.id)"
                    v-if="!isEncryptField(product.name) && canSeeCustomer"
                  >{{ product.name }}</span>
                  <span v-else>{{ product.name }}</span>
                  <!-- <el-tooltip v-if="product.id" placement="top"> -->
                  <el-tooltip v-if="showProductRelationCount(product)" placement="top">
                    <div slot="content" v-html="$t('task.detail.components.unfinishedAndAllTask', {unfinished: productRelationCount[product.id].unfinished, all: productRelationCount[product.id].all})"></div>
                    <el-button class="relation-count-button" @click="openProductView(product.id)" v-track="$track.formatParams('CHECK_PRODUCT_EVENT_NUM')">
                      {{ `${productRelationCount[product.id].unfinished}/${productRelationCount[product.id].all}` }}
                    </el-button>
                  </el-tooltip>
                </div>
              </div>
              <!-- 数据有误一直没能展示，但是默认会有灰色横条，先给注释掉，等后续事件方面有产品关联字段相关改造再确认 -->
              <!-- <div class="product-item-relation" v-if="event.products.length == 1 && relationProductfields.length">
                <form-view class="form-view-two-column" :fields="relationProductfields" :value="event"></form-view>
              </div> -->
            </div>
          </div>
        </template>
        <!-- end 产品 -->
      </template>
      <!-- end 客户 -->

      <!-- start 负责人 -->
      <template slot="executorName" slot-scope="{ field }">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">
            <span v-user="event.executorId" class="user-card-triggle">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="event.executorStaffId"></open-data>
              </template>
              <template v-else>
                {{ event.executorName }}
              </template>
            </span>
          </div>
        </div>
      </template>
      <!-- end 负责人 -->

      <!-- start 协同人 -->
      <template slot="synergies" slot-scope="{ field, value }" v-if="allowModifySynergy || (value && value.length > 0)">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">
            <span class="synergies-name mar-r-10 user-card-triggle" v-for="item in value" :key="item.userId" v-user="item.userId">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="item.staffId"></open-data>
              </template>
              <template v-else>
                {{ item.displayName }}
              </template>
            </span>
            <template v-if="event.isDelete === 0&&hasxtrEdit">
              <el-tooltip class="item" effect="dark" :content="$t('common.event.actionStatus.updateSynergy')" placement="top">
                <i class="iconfont icon-bianji1" @click="modifySynergies"></i>
              </el-tooltip>
            </template>
          </div>
        </div>
      </template>
      <!-- end 协同人 -->

      <!-- start 事件状态 -->
      <template slot="state" slot-scope="{ field }">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">
            <div class="event-state" :style="{'background-color': stateColor.bgColor, 'color': '#FFF'}">{{ stateText }}</div>
          </div>
        </div>
      </template>
      <!-- end 事件状态 -->

      <!-- start 创建人 -->
      <template slot="createUser" slot-scope="{ field }">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">
            <template v-if="event.source === '客户自助'">{{ getSoureceLabel(event.source) }}</template>
            <template v-if="event.source === '手动创建' || event.source === 'API创建' || event.source === '导入创建' || event.source === '系统创建'">
              <span v-user="event.createUserId" class="user-card-triggle">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="event.createUserStaffId"></open-data>
                </template>
                <template v-else>
                  {{ event.createUserName }}
                </template>
              </span>
            </template>
          </div>
        </div>
      </template>
      <!-- end 创建人 -->
      
      <!-- 创建方式 -->
      <template slot="source" slot-scope="{ field }" v-if="event.source">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">
            {{getSoureceLabel(event.source)}}
          </div>
        </div>
      </template>
      <!-- end 创建方式 -->
    </form-view>
</div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform'
import * as EventApi from '@src/api/EventApi.js';
import EventStateEnum from '@model/enum/EventStateEnum.ts';
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'
import { chooseExUser } from '@model/config/SelectUserConfig.ts'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { EventCreateMethodLabelEnum } from '@model/enum/LabelEnum.ts';
import FormCellChange from '@src/component/compomentV2/FormCellChange/index.vue';

import { customerTagValue, customerLabel } from '@src/modules/customer/util/customer.js'
export default {
  name: 'event-info',
  props:{
    fields: {
      type: Array,
      default: ()=> []
    },
    event: {
      type: Object,
      default: ()=> {}
    },
    cusMatchMap: {
      type: Object,
      default: ()=> {}
    },
    canSeeCustomer: {
      type: Boolean,
      default: false
    },
    hasCusCreate: {
      type: Boolean,
      default: false
    },
    doorGray: {
      type: Boolean,
      default: false
    },
    auto: {
      type: Object,
      default: ()=> {}
    },
    showAssignButton: { // 允许展示分配按钮
      type: Boolean,
      default: false
    },
    formCellCount:{
      type:Number,
      default:1
    },
  },

  computed: {
    allowModifySynergy(){
      return this.hasxtrEdit && !this.isApproving && !this.eventStatePause;
    },
    eventStatePause(){
      return this.event.isPaused === 1
    },
    // 是否正在审批中
    isApproving(){
      return this.event.inApprove == 1;
    },
    haxEdit(){
      return this.auto.CASE_EDIT == 3
    },
    hasxtrEdit(){
      return this.haxEdit || ( this.auto.CASE_EDIT == 1 && this.isCreator);
    },
    isCreator(){
      return this.event.createUserId == localStorage.getItem('userId');
    },
    /** 
    * @description 事件状态
    */
    stateText() {
      return EventStateEnum.getNameForEvent(this.event);
    },

    /** 
    * @description 事件状态颜色
    */
    stateColor() {
      return EventStateEnum.getColorForEvent(this.event);
    },

    /** 
    * @description 产品关联字段
    */
    relationProductfields() {
      return this.fields.filter(field => field.formType == 'relationProduct');
    },

    /** 
    * @description 客户字段 
    */
    customerField() {
      return this.fields.filter(f => f.fieldName === 'customer')[0];
    },
    
    /** 
    * @description 客户字段配置 
    */
    customerOption() {
      return this.customerField?.setting?.customerOption || {};
    },
    isAddExist() {
      return this.cusMatchMap.isAddExist || false;
    },
    isCusExist() {
      return this.cusMatchMap.isCusExist || false;
    },
    isLmExist() {
      return this.cusMatchMap.isLmExist || false;
    },
  },
  
  data() {
    return {
      isOpenData,
      eventRelationCount: {},
      customerRelationCount: {},
      productRelationCount: {},
    }
  },
  created() {
    this.getCustomerRelationCount()
    if (this.canSeeCustomer) {
      this.getProductRelationCount()
    }
  },
  methods: {
    // 获取客户相关事件数
    async getCustomerRelationCount() {
      this.customerRelationCount = await EventApi.getCountForCreate({module:'customer', id: this.event.cusId})
    },

    // 获取产品相关事件数
    getProductRelationCount() {
      this.event.products.forEach(async item => {
        await EventApi.getCountForCreate({module:'product', id: item.id})
          .then(res => {
            this.$set(this.productRelationCount, item.id, res);
          })
      })
    },

    // 保存客户信息
    saveCusInfo() {
      this.$emit('eventInfoSaveCusInfo')
    },

    // 保存联系人
    saveLinkman() {
      this.$emit('eventInfoSaveLinkman');
    },

    /** 
    * @description 打开产品详情
    */
    openProductView(productId) {
      let fromId = window.frameElement.getAttribute('id');

      if(!productId) return;
      
      // this.$platform.openTab({
      //   id: `product_view_${productId}`,
      //   title: '产品详情',
      //   close: true,
      //   url: `/customer/product/view/${productId}?noHistory=1`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductView,
        key: productId,
        params: 'noHistory=1',
        fromId
      })
    },

    /** 
    * @description 是否显示产品关联的工单数量
    * 1. 全部数量>0
    * 2. 且未加密
    */
    showProductRelationCount(product) {
      let { id, name } = product;
      if(Object.keys(this.productRelationCount).length > 0) {
        let { all } = this.productRelationCount[id];
        return Number(all) > 0 && !this.isEncryptField(name);
      } 
      return false
      
    },

    /**
    * @description 是否加密字段
    */
    isEncryptField(value) {
      return value === '***';
    },

    // 打开客户新tab
    openCustomer() {
      const customerId = this.event.cusId

      // this.$platform.openTab({
      //   id: `customer_view_${customerId}`,
      //   title: '客户详情',
      //   close: true,
      //   url: `/customer/view/${customerId}?noHistory=1`,
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params: 'noHistory=1',
      })
    },

    // 修改协同人
    modifySynergies() {
      let options = {
        title: this.$t('common.event.actionStatus.updateSynergy'),
        selectedUsers: this.event.synergies,
        max: 100,
        ...chooseExUser,
        mode: BaseSelectUserModeEnum.Filter
      };

      // 分配传authKey 区分全部权限和团队权限
      if(this.showAssignButton) {
        options.authKey = 'CASE_ALLOT';
      }
      
      return this.$fast.select.multi.all(options).then(result => {
        if(result.status == 0) {
          let synergies = result?.data?.users || [];
          const params = { id	: this.event.id, synergies }
          
          EventApi.eventUpdateSynergy(params).then(res => {
            if (res.status === 0) {
              this.event.synergies = synergies;
              this.$emit('updateRecord')
            } else {
              this.$notify({
                title: this.$t('common.base.error'),
                message: res.message,
                type: 'error'
              });
            }
          }).catch(err => console.error(err))
        }
      })
        .catch(err => console.error(err))
    },
    // 获取创建方式的多语言label
    getSoureceLabel(key) {
      return EventCreateMethodLabelEnum[key] || key
    },
    customerTagValue,
    customerLabel,
  },
  components: {
    FormCellChange
  },
}
</script>

<style lang="scss" scoped>

.link {
  @include fontColor();
  cursor: pointer;
  display: inline-block;
}

.event-state {
    width: 52px;
    min-width: 52px;
    height: 22px;
    line-height: 22px;
    font-size: 12px;
    text-align: center;
    border: 1px solid;
    border-radius: 11px;
}
// 客户、产品关联工单数量
.relation-count-button {
  height: 18px;
  line-height: 18px;
  padding: 0 6px;
  margin: 0 8px 0;
  
  font-size: $font-size-small;
  color: $text-color-regular;
  
  background: $color-border-l2;
  border-radius: 2px;
  cursor: pointer;
}

.product-list {
  .product-item {
    &-name {
      line-height: 20px;
      display: flex;
      align-items: baseline;
      span {
        margin-right: 0;
      }
    }
    &-relation {
      margin-top: 8px;
      padding: 6px 10px;
      background-color: $bg-color-l3;
      border-radius: $border-radius-base;
      .form-view {
        background-color: $bg-color-l3;
      }
    }
    &:not(:last-child) {
      .product-item-name {
        margin-bottom: 8px;
      }
      .product-item-relation {
        margin-bottom: 16px;
      }
    }
  }
}

.customer-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  &-wrap {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    .customer-name {
      @include text-ellipsis();
      word-wrap: break-word;
      white-space: normal;
    }
  }
}
</style>
